package org.moonshiner.ctci.c1.q5;

public class StringCompressor {

	public String compressString(String inputString){
		
		int size = countSize(inputString);
		
		if(size > inputString.length()){
			return inputString;
		}
		
		StringBuilder builder = new StringBuilder();
		
		char last = inputString.charAt(0);
		int count = 1;
		
		for(int i = 1; i < inputString.length(); i++){
			if(last == inputString.charAt(i)){
				count++;
			}else{
				builder.append(last).append(count);
				last = inputString.charAt(i);
				count = 1;
			}
		}
		
		
		builder.append(last).append(count);
		
		
		return builder.toString();
	}

	private int countSize(String inputString) {
		int size = 0;
		
		char last = inputString.charAt(0);
		int count = 1;
		
		for (int i = 1; i < inputString.length(); i++) {
			
			if(inputString.charAt(i) == last){
				count++;
			}else{
				size += 1 + String.valueOf(count).length();
				last = inputString.charAt(i);
				count = 1;
			}
			
		}
		
		size += 1 + String.valueOf(count).length();
		
		return size;
	}
}
